import { defineStore } from 'pinia';

interface CartItem {
  id: number;
  title: string;
  price: number;
  cover: string;
  duration: string;
  quantity: number;
}

export const useCartStore = defineStore('cart', {
  state: () => ({
    items: [] as CartItem[],
  }),
  getters: {
    totalItems: (state) => state.items.reduce((sum, item) => sum + item.quantity, 0),
    totalPrice: (state) => state.items.reduce((sum, item) => sum + item.price * item.quantity, 0),
  },
  actions: {
    addItem(route: { id: number; title: string; price: number; cover: string; duration: string }) {
      const existingItem = this.items.find((item) => item.id === route.id);
      if (existingItem) {
        existingItem.quantity++;
      } else {
        this.items.push({ ...route, quantity: 1 });
      }
    },
    removeItem(id: number) {
      const index = this.items.findIndex((item) => item.id === id);
      if (index !== -1) {
        if (this.items[index].quantity > 1) {
          this.items[index].quantity--;
        } else {
          this.items.splice(index, 1);
        }
      }
    },
    clearCart() {
      this.items = [];
    },
  },
});